package com.wt.chat.file;

import com.wt.chat.exception.BaseException;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.UUID;

/**
 * @description
 * @author: wangtao
 * @date:16:25 2019/12/5
 * @email:taow02@jumei.com
 */
public class LocalFileStoreSystem implements FileStoreSystem {

	private String path;

	public LocalFileStoreSystem() {
	}

	public LocalFileStoreSystem(String path) {
		this.path = path;
	}

	@Override
	public String save(InputStream is, String sourceFileName) {
		String fileName = UUID.randomUUID().toString().replace("-", "") + sourceFileName
				.substring(sourceFileName.lastIndexOf("."));
		String realPath = path + "/" + fileName;
		try {
			FileOutputStream fos = new FileOutputStream(realPath);
			byte[] b = new byte[10240];
			int len = 0;
			while (true) {
				if ((len = is.read(b)) == -1) {
					break;
				}
				fos.write(b, 0, len);
			}
			fos.flush();
			return "/message/file/get?path=" + URLEncoder.encode(realPath, "utf-8");
		} catch (Exception e) {
			throw new BaseException("存储失败," + e.getMessage());
		}
	}

	@Override
	public InputStream get(String path) {
		try {
			return new FileInputStream(path);
		} catch (Exception e) {
			throw new BaseException("获取失败," + e.getMessage());
		}
	}

}
